//视频文件后缀名
let videoExtNames = ['mp4', 'avi', "mov"];

/**
 * 获取拓展名
 * @param fileName 文件名称
 */
export function getExtName(fileName) {
    if (fileName.lastIndexOf('.') < 0) {
        return null;
    }
    return fileName.substring(fileName.lastIndexOf('.') + 1);
}

/**
 * 是否为ts文件
 */
export function isTsVideo(fileName) {
    return getExtName(fileName) === 'ts';
}

/**
 * 获取视频第一帧
 * @param videoUrl 视频url
 * @returns {Promise<unknown>}
 */
export function getVideoFirstFrame(videoUrl) {
    return new Promise((resolve, reject) => {
        var video = document.createElement('video');

        // 定义事件监听器函数
        function loadedMetadataHandler() {
            video.currentTime = 0;
        }

        function seekedHandler() {
            var canvas = document.createElement('canvas');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            var dataURL = canvas.toDataURL('image/png');
            resolve(dataURL);

            // 移除事件监听器
            video.removeEventListener('loadedmetadata', loadedMetadataHandler);
            video.removeEventListener('seeked', seekedHandler);

            // 清理
            video.src = '';
            canvas = null;
        }

        // 添加事件监听器
        video.addEventListener('loadedmetadata', loadedMetadataHandler);
        video.addEventListener('seeked', seekedHandler);
        video.src = videoUrl;
        video.load();
        video.onerror = function () {
            reject(new Error('Failed to load the video.'));
        };
    });
}

export async function getTsVideoFirstFrame(url) {
    return new Promise((resolve) => {
        const canvas = document.createElement("canvas");
        let player = new JSMpeg.Player(url, {
            canvas: canvas,
            decodeFirstFrame: true,
            loop: false,
            video: true,
            progressive: false,
            audio: false,
            autoplay: true,
            onSourceCompleted() {
                setTimeout(() => {
                    // let width = player.renderer.width;
                    // let height = player.renderer.height;
                    let dataURL = canvas.toDataURL('image/png');
                    resolve(dataURL);
                    player.destroy();
                }, 1000);
            }
        });
    });
}

/**
 * 是否视频
 * @param fileName
 * @returns {boolean}
 */
export function isVideo(fileName) {
    let extName = getExtName(fileName);
    return videoExtNames.includes(extName);
}